<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="工号" prop="jobNumber">
        <el-input
          v-model="queryParams.jobNumber"
          placeholder="请输入工号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="designerPersonName">
        <el-input
          v-model="queryParams.designerPersonName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="电子卡号" prop="cardNumber">
        <el-input
          v-model="queryParams.cardNumber"
          placeholder="请输入电子卡号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="orgDeptName">
        <el-input
          v-model="queryParams.orgDeptName"
          placeholder="请输入所属部门"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="所属班组" prop="orgTeamName">
        <el-input
          v-model="queryParams.orgTeamName"
          placeholder="请输入所属班组"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="在职状态" prop="dictStaffStatus">
        <el-select
          v-model="queryParams.dictStaffStatus"
          placeholder="请选择在职状态"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions('dict_staff_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入职日期" prop="entryDate">
        <el-date-picker
          v-model="time"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="width: 100%; height: 50px; display: flex; justify-content: space-between">
    <div>
      
      <el-button
        type="primary"
        @click="showImport"
        v-hasPermi="['config:drawing-designer:import']"
      >
         数据导入
      </el-button>
      <el-button
        type="primary"
        @click="handleExport"
        :loading="exportLoading"
        v-hasPermi="['config:drawing-designer:export']"
      >
         数据导出
      </el-button>
      <el-button
        type="primary"
        @click="openForm('create')"
        v-hasPermi="['config:drawing-designer:create']"
      >
        新增
      </el-button>
    </div>
    <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
  </div>
    <Table
      :columns="tableTitleList"
      :selection="tableObject.tableList.length ? true : false"
      @register="tableoperation"
      @update:currentPage="getTableData"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.pageNo"
      :tableHeight="tableHeight"
    >
      <template #action="{ row }">
        <el-button
          link
          type="primary"
          @click="openForm('update', row.id)"
          v-hasPermi="['config:drawing-designer:update']"
        >
          编辑
        </el-button>
        <el-button
          link
          type="danger"
          @click="handleDelete(row.id)"
          v-hasPermi="['config:drawing-designer:delete']"
        >
          删除
        </el-button>
      </template>
    </Table>
  </ContentWrap>
  <!-- 上传文件 -->
  <CusUploadFile ref="cusUploadFile" @refresh="getList" :onlyUpdate="true"/>
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getLabelAll" />
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表单弹窗：添加/修改 -->
  <DrawingDesignerForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts" name="DrawingDesigner">
import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { getIntDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import * as DrawingDesignerApi from '@/api/config/drawingDesigner'
import DrawingDesignerForm from './DrawingDesignerForm.vue'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
let tableTitleList = reactive<CrudSchema[]>([]) // 表头的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  jobNumber: null,
  designerPersonName: null,
  mobile: null,
  cardNumber: null,
  entryDate: null,
  dictStaffStatus: null,
  orgDeptName: null,
  orgTeamName: null
})
const time = ref([]) //时间筛选
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// tableObject：表格的属性对象，可获得分页大小、条数等属性
// tableMethods：表格的操作对象，可进行获得分页、删除记录等操作getUserLabelPage
// 详细可见：https://doc.iocoder.cn/vue3/crud-schema/
const { tableObject, tableMethods } = useTable({
  getListApi: DrawingDesignerApi.getDrawingDesignerPage, // 分页接口
  defaultParams: queryParams
})

/**表头数据 */
const getLabelAll = async () => {
  try {
    const data = await DrawingDesignerApi.getDrawingDesignerPage(queryParams)
    const { allSchemas } = useCrudSchemas(data.labels)
    allSchemas.tableColumns.push({
      label: '操作',
      field: 'action',
      isDetail: false,
      width: 110
    })
    tableTitleList = allSchemas.tableColumns
    /**表头修改需要刷新表格 */
    getList()
  } finally {
  }
}

// 获得表格的各种操作
const { getList } = tableMethods

/** 查询列表 */
const getTableData = (val) => {
  tableObject.currentPage = val

  getList()
}

/**表头内部方法 */
const usTableoperation = ref()
   const tableoperation = (parent: any) => {
     usTableoperation.value = parent
   }

/**导入显示 */
const cusUploadFile = ref()
const showImport = () => {
  cusUploadFile.value.open(
    '/config/drawing-designer/get-import-template',
    '/config/drawing-designer/import'
  )
}

// 导出
const downloadFun = async () => {
  const val = exportRef.value.params
  let params = {
    fileName: val.name,
    ids: ''
  }
  if (val.range === 'all') {
    params.ids = ''
  } else {
    params.ids = usTableoperation.value.selections.map((item) => item.id)
  }
  console.log(params)
  DrawingDesignerApi.exportDrawingDesigner(params).then((res) => {
    download.excel(res, val.name)
    clearSelectData()
  })
}

//清空多选
const clearSelectData = () => {
   usTableoperation.value.selections = []
     usTableoperation.value.clearTableSelect()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  if (time.value.length) {
    const date = JSON.parse(JSON.stringify(time.value))
    queryParams.entryDate = date.join(',')
  } else {
    queryParams.entryDate = null
  }

  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  time.value = []
  tableObject.params = queryParams
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DrawingDesignerApi.deleteDrawingDesigner(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = () => {
  exportRef.value.open()
}

/**打开表格表头设置**/
const tableTitleSet = ref()
const openTableTitleSet = () => {
  let code = 'DrawingDesigner'
  tableTitleSet.value.open(tableTitleList, code)
}
/** 初始化 **/
/** 初始化 **/
const tableHeight = ref(0)
   //132：表格内除表格以外的高度，127 顶部固定高度 + copyright高度
   onMounted(async () => {
     const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
     tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 127
  await getLabelAll()
  getList()
})
</script>
